package com.kdtech.analyse.news;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.RegexUtils;
import com.kdtech.utils.StringUtils;
import com.kdtech.utils.HtmlCleaner;

/**
 * 珠海新闻网解析类
 * @author kd-15
 */
public class HizhNewsAnalyse implements AnalyseNews{
	
	private static final String[] regex={
		"http://www.hizh.cn/[a-z]*/[0-9]*.jhtml",
		"http://auto.hizh.cn/news/[0-9]*/story_[0-9]*.html",
		"http://auto.hizh.cn/news/storys_[0-9]*.html"
	};	
	
	
	public boolean isDetailPage(String url) {
		return RegexUtils.matchAnyIgnoreCase(url, regex);
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		if (urlMeta.getHtml() == null) {
		}		
		NewsMeta news=new NewsMeta();
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();	
		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);				
		news.setUrl(url);	
		
		title =doc.select("div#article h1").text();	
		if(StringUtils.isBlank(title)){
			title =doc.select("div.ina_news_text h1 p b").text();	
		}
		content=HtmlCleaner.getContentHtml(url,doc.select("div.entry-content"));			
		if(StringUtils.isBlank(content)){
			content=HtmlCleaner.getContentHtml(url,doc.select("div.ina_news_pic_text"));			
		}
		
		String authorStr = doc.select("span.news_icon").text();
		if(StringUtils.isNotBlank(authorStr)){
			author = StringUtils.substringAfter(authorStr, "来源：");
		}
		
		date=DateUtils.matchDate(doc.select("span.pub-date").text());
		if(date==null){
			date=DateUtils.matchDate(doc.select("span.ina_data").text());
		}
		if (StringUtils.isNotBlank(title) && date!=null){			
			news.setTitle(StringUtils.trimSpace(title));
			news.setContent(content);
			news.setAuthor(author);
			news.setDate(date);	
			news.setType(1);	
		}
		return news;
	}	
	public static void main(String[] args) {
		String url="http://auto.hizh.cn/news/20150729/story_899878.html";
		HizhNewsAnalyse analyse=new HizhNewsAnalyse();		
		System.out.println(analyse.isDetailPage(url));
		UrlMeta meta=CrawlHTML.responseToURL(url);
		System.out.println(analyse.parserHtml(meta));
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	
	public boolean isNeedUpdate(){
		return false;
	}
}
